<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>js数据类型的判断 | 一枚前端小菜鸟的博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="JS中数据类型的判断（ typeof，instanceof，constructor，Object.prototype.toString.call()（1）typeoftypeof 对于原始类型来说，除了 null 都可以显示正确的类型 12345678console.log(typeof 2);               &#x2F;&#x2F; numberconsole.log(typeof true);">
<meta property="og:type" content="article">
<meta property="og:title" content="js数据类型的判断">
<meta property="og:url" content="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/18/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%88%A4%E6%96%AD/index.html">
<meta property="og:site_name" content="一枚前端小菜鸟的博客">
<meta property="og:description" content="JS中数据类型的判断（ typeof，instanceof，constructor，Object.prototype.toString.call()（1）typeoftypeof 对于原始类型来说，除了 null 都可以显示正确的类型 12345678console.log(typeof 2);               &#x2F;&#x2F; numberconsole.log(typeof true);">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fe.che300.com/easymock/upload/2020/07/17/5b12b0ac91cde488668330585c1ef71c.png">
<meta property="article:published_time" content="2021-06-18T05:57:40.000Z">
<meta property="article:modified_time" content="2021-06-18T05:58:01.902Z">
<meta property="article:author" content="yywei">
<meta property="article:tag" content="菜鸟,前端,js,react,vue">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fe.che300.com/easymock/upload/2020/07/17/5b12b0ac91cde488668330585c1ef71c.png">
  
    <link rel="alternate" href="/atom.xml" title="一枚前端小菜鸟的博客" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 5.4.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">一枚前端小菜鸟的博客</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">yywei的遇坑记录</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS 订阅"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="搜索"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://gitee.com/weiyayun1995/weiyayun1995.git"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-js数据类型的判断" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/06/18/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%88%A4%E6%96%AD/" class="article-date">
  <time class="dt-published" datetime="2021-06-18T05:57:40.000Z" itemprop="datePublished">2021-06-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      js数据类型的判断
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h2 id="JS中数据类型的判断（-typeof，instanceof，constructor，Object-prototype-toString-call"><a href="#JS中数据类型的判断（-typeof，instanceof，constructor，Object-prototype-toString-call" class="headerlink" title="JS中数据类型的判断（ typeof，instanceof，constructor，Object.prototype.toString.call()"></a>JS中数据类型的判断（ typeof，instanceof，constructor，Object.prototype.toString.call()</h2><h3 id="（1）typeof"><a href="#（1）typeof" class="headerlink" title="（1）typeof"></a>（1）typeof</h3><p>typeof 对于原始类型来说，除了 null 都可以显示正确的类型</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="number">2</span>);               <span class="comment">// number</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="literal">true</span>);            <span class="comment">// boolean</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="string">&#x27;str&#x27;</span>);           <span class="comment">// string</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> []);              <span class="comment">// object     []数组的数据类型在 typeof 中被解释为 object</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;);    <span class="comment">// function</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> &#123;&#125;);              <span class="comment">// object</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="literal">undefined</span>);       <span class="comment">// undefined</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="literal">null</span>);            <span class="comment">// object     null 的数据类型被 typeof 解释为 object</span></span><br></pre></td></tr></table></figure>
<p>typeof 对于对象来说，除了函数都会显示 <code>object</code>，所以说 <code>typeof</code>并不能准确判断变量到底是什么类型,所以想判断一个对象的正确类型，这时候可以考虑使用 <code>instanceof</code></p>
<h3 id="（2）instanceof"><a href="#（2）instanceof" class="headerlink" title="（2）instanceof"></a>（2）instanceof</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="number">2</span> <span class="keyword">instanceof</span> <span class="built_in">Number</span>);                    <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="literal">true</span> <span class="keyword">instanceof</span> <span class="built_in">Boolean</span>);                <span class="comment">// false </span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;str&#x27;</span> <span class="keyword">instanceof</span> <span class="built_in">String</span>);                <span class="comment">// false  </span></span><br><span class="line"><span class="built_in">console</span>.log([] <span class="keyword">instanceof</span> <span class="built_in">Array</span>);                    <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125; <span class="keyword">instanceof</span> <span class="built_in">Function</span>);       <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log(&#123;&#125; <span class="keyword">instanceof</span> <span class="built_in">Object</span>);                   <span class="comment">// true    </span></span><br><span class="line"><span class="comment">// console.log(undefined instanceof Undefined);      // error</span></span><br><span class="line"><span class="comment">// console.log(null instanceof Null);                // error</span></span><br></pre></td></tr></table></figure>
<p>可以看出直接的字面量值判断数据类型，<code>instanceof</code>可以精准判断引用数据类型<code>（Array，Function，Object）</code>，而基本数据类型不能被<code>instanceof</code>精准判断。</p>
<p>我们来看一下 <code>instanceof</code> 在MDN中的解释：<code>instanceof</code> 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 <code>prototype</code> 属性。其意思就是判断对象是否是某一数据类型（如<code>Array</code>）的实例，请重点关注一下是判断一个对象是否是数据类型的实例。在这里字面量值，2， <code>true</code> ，’<code>str</code>‘不是实例，所以判断值为false。</p>
<h3 id="（3）constructor"><a href="#（3）constructor" class="headerlink" title="（3）constructor"></a>（3）constructor</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log((<span class="number">2</span>).constructor === <span class="built_in">Number</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log((<span class="literal">true</span>).constructor === <span class="built_in">Boolean</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log((<span class="string">&#x27;str&#x27;</span>).constructor === <span class="built_in">String</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log(([]).constructor === <span class="built_in">Array</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log((<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;).constructor === <span class="built_in">Function</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log((&#123;&#125;).constructor === <span class="built_in">Object</span>); <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>这里有一个坑，如果我创建一个对象，更改它的原型，constructor就会变得不可靠了</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Fn</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">Fn.prototype=<span class="keyword">new</span> <span class="built_in">Array</span>();</span><br><span class="line"><span class="keyword">var</span> f=<span class="keyword">new</span> Fn();</span><br><span class="line"><span class="built_in">console</span>.log(f.constructor===Fn);    <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(f.constructor===<span class="built_in">Array</span>); <span class="comment">// true </span></span><br></pre></td></tr></table></figure>

<h3 id="（4）Object-prototype-toString-call"><a href="#（4）Object-prototype-toString-call" class="headerlink" title="（4）Object.prototype.toString.call()"></a>（4）Object.prototype.toString.call()</h3><p>使用 Object 对象的原型方法 toString ，使用 call 进行狸猫换太子，借用Object的 toString 方法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="built_in">Object</span>.prototype.toString;</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="number">2</span>));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="literal">true</span>));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="string">&#x27;str&#x27;</span>));</span><br><span class="line"><span class="built_in">console</span>.log(a.call([]));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(&#123;&#125;));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="literal">undefined</span>));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="literal">null</span>));</span><br></pre></td></tr></table></figure>
<p>执行结果：<img src="https://fe.che300.com/easymock/upload/2020/07/17/5b12b0ac91cde488668330585c1ef71c.png"></p>
<blockquote>
<p>其实 null 不是对象，虽然 typeof null 会输出 object，但是这只是 JS 存在的一个悠久 Bug。在 JS 的最初版本中使用的是 32 位系统，为了性能考虑使用低位存储变量的类型信息，000 开头代表是对象，然而 null 表示为全零，所以将它错误的判断为 object 。虽然现在的内部类型判断代码已经改变了，但是对于这个 Bug 却是一直流传下来。</p>
</blockquote>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/18/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%88%A4%E6%96%AD/" data-id="ckq7mlsva000adgt9gaql8nq6" data-title="js数据类型的判断" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2021/06/18/sendbeacon/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">前一篇</strong>
      <div class="article-nav-title">
        
          sendbeacon
        
      </div>
    </a>
  
  
    <a href="/2021/06/18/%E8%84%B1%E6%95%8F/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">后一篇</strong>
      <div class="article-nav-title">脱敏</div>
    </a>
  
</nav>

  
</article>


</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/06/">六月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/05/">五月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/04/">四月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/03/">三月 2021</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/06/22/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%8F%8A%E8%BD%AC%E6%8D%A2/">js数据类型及转换</a>
          </li>
        
          <li>
            <a href="/2021/06/18/react-hook-%E9%A1%B9%E7%9B%AE%E4%B8%AD%E5%AE%9E%E8%B7%B5/">react-hook 项目中实践</a>
          </li>
        
          <li>
            <a href="/2021/06/18/%E6%95%B0%E5%AD%97%E7%AD%BE%E5%90%8D/">数字签名</a>
          </li>
        
          <li>
            <a href="/2021/06/18/sendbeacon/">sendbeacon</a>
          </li>
        
          <li>
            <a href="/2021/06/18/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%88%A4%E6%96%AD/">js数据类型的判断</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2021 yywei<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/js/jquery-3.4.1.min.js"></script>



  
<script src="/fancybox/jquery.fancybox.min.js"></script>




<script src="/js/script.js"></script>





  </div>
</body>
</html>